package com.visizen.wisdomclass.server.action.User;

import com.alibaba.fastjson.JSONObject;
import com.visizen.wisdomclass.server.action.response.Result;
import com.visizen.wisdomclass.server.annotation.ValidateToken;
import com.visizen.wisdomclass.server.model.WcEquipment;
import com.visizen.wisdomclass.server.model.WcUser;
import com.visizen.wisdomclass.server.service.EquipmentService;
import com.visizen.wisdomclass.server.service.LoginLogService;
import com.visizen.wisdomclass.server.token.WCTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 【用户】 使用Token进行静默登录
 *
 * @author: chenjian
 */
@Controller
@RequestMapping("/User")
public class UserLoginByTokenAction {
    /**
     * 使用Token进行登录，主要是用于APP免登录作用，当Token超时或错误后才进入正常登录模式。<br/>
     * 该API的主要目的是为了能够让用户每次打开APP都能实时更新设备UUID以便于推送内容
     *
     * @param token
     * @param equipUUID
     * @param request
     * @return
     */
    @ValidateToken
    @RequestMapping(value = "/loginByToken", method = RequestMethod.POST)
    @ResponseBody
    public Result loginByToken(@RequestParam(required = true) String token,
                               @RequestParam(required = true) String equipUUID,
                               HttpServletRequest request) {
        Result result = new Result();
        WcUser user = (WcUser) tokenManager.getToken(token).getSource();
        WcEquipment equipment = equipmentService.selectByUUID(equipUUID);
        loginLogService.newLoginByTokenLog(user.getUser_id(), equipment.getEquip_id());
        JSONObject jo = new JSONObject();
        jo.put("token", token);
        result.setSuccessResult(request, "", jo);
        return result;
    }

    private LoginLogService loginLogService;
    private WCTokenManager tokenManager;
    private EquipmentService equipmentService;

    @Autowired
    public void setEquipmentService(EquipmentService equipmentService) {
        this.equipmentService = equipmentService;
    }

    @Autowired
    public void setTokenManager(WCTokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Autowired
    public void setLoginLogService(LoginLogService loginLogService) {
        this.loginLogService = loginLogService;
    }
}
